package com.qf.user.controller;

import com.qf.dto.PageDto;
import com.qf.user.entity.User;
import com.qf.user.mapper.UserMapper;
import com.qf.user.service.UserService;
import com.qf.user.service.impl.UserServiceImpl;
import com.qf.utils.JWTUtil;
import com.qf.vo.PageResult;
import com.qf.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 管理员用户表 前端控制器
 * </p>
 *
 * @author XJJ
 * @since 2023-10-30
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    UserServiceImpl userServiceimpl;

    /*token验证*/
    @GetMapping ("/verifyToken")
    public Result verifyToken(@RequestHeader("token") String token){
        try {
            JWTUtil.parseToken(token);
            return new Result(0,"valid token");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1,"invalid token");
        }
    }

    /*登录*/
    @RequestMapping("/login")
    public Result login(@RequestBody User user) {
        return userService.login(user);
    }

    /*注册*/
    @PostMapping("/register")
    public  Result register(@RequestBody  User user){
        return userService.addUser( user);
    }

    /*登出*/
    @PostMapping("/logout")
    public void logout(){
        SecurityContextHolder.clearContext();
    }

    //查询全部
    @PostMapping("/list")
    public PageResult<User> list(@RequestBody PageDto<User> pageDto){
        return userServiceimpl.page(pageDto);
    }
    //删除
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        userMapper.delete(id);
        return new Result(0,"success");
    }
//    //根据id查询
//    @GetMapping("findById/{id}")
//    public Result findById(@PathVariable Long id){
//        final User user = userMapper.selectById(id);
//        return new Result(0,"success",user);
//    }
    //修改
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        final int id = userMapper.updateById(user);
        return new Result(0,"success");
    }
    //添加
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insert(user);
        return new Result(0,"success");
    }
}
